//
//  Forgot_ViewController.m
//  chilemat
//
//  Created by Cristian Gonzalez Figueroa on 24-10-14.
//  Copyright (c) 2014 Chilemat SpA. All rights reserved.
//

#import "Forgot_ViewController.h"
#import "dao.h"

@interface Forgot_ViewController ()

@end

@implementation Forgot_ViewController

@synthesize textEmail;
@synthesize json;
@synthesize viewSaving;

NSTimer *timerForgotPassword;

-(BOOL)textFieldShouldReturn:(UITextField *)textField {
    

    [self.view endEditing:YES];
    
    return YES;
}

-(void) touchesBegan :(NSSet *) touches withEvent:(UIEvent *)event{
    
    [self.view endEditing:YES];
    
    [super touchesBegan:touches withEvent:event ];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self.navigationController.navigationBar setBackIndicatorImage:[UIImage imageNamed:@"icono_atras.png"]];
    
    self.textEmail.delegate = self;
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (IBAction)backAction:(id)sender {

    [self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:1] animated:YES];
    
}

- (IBAction)callNumber:(id)sender {
    
    NSString *strContactPhone;
    
    dao *objDAO = [[dao alloc] init];
    
    strContactPhone = [NSString stringWithFormat:@"tel://%@", [objDAO obtainCallCenterNumber]];
    
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:strContactPhone]];
    
}

-(NSString *) transformarCaracteresComposables: (NSString *)string{
    
    NSString *strStringTransformado = @"";
    //  NSString *strStringGeneral = @"";
    int intLargoString = 0;
    
    intLargoString = (int) string.length;
    
    for (int i=0; i < intLargoString; i++) {
        
        unichar c = [string characterAtIndex:i];
        NSLog(@"c=%C", c);
        
        if ([[NSCharacterSet decomposableCharacterSet] characterIsMember:c]) { //Si es con acentos la letra
            
            CFStringRef originalString = (__bridge CFStringRef)([NSString stringWithCharacters:&c length:1]);
            CFStringRef encodedString = CFURLCreateStringByAddingPercentEscapes(
                                                                                kCFAllocatorDefault,
                                                                                originalString,
                                                                                NULL,
                                                                                CFSTR(":/?#[]@!$&'()*+,;="),
                                                                                kCFStringEncodingUTF8);
            
            strStringTransformado = [NSString stringWithFormat:@"%@%@", strStringTransformado, encodedString];
        }else{
            strStringTransformado =  [NSString stringWithFormat:@"%@%@", strStringTransformado, [NSString stringWithCharacters:&c length:1]];
            
        }
        
    }
    
    NSLog(@"strStringTransformado=%@", strStringTransformado);
    
    return strStringTransformado;
}

- (void) sendRestorePassword:(NSTimer *) timer {
    
    //Detenemos el timer
    [timerForgotPassword invalidate];

    dao *objDAO = [[dao alloc] init];
    int intIdUser;
    
    intIdUser = [objDAO obtainCurrentIdUser];
    
    NSString *stringReplace = @"";
    
    stringReplace = [self transformarCaracteresComposables:textEmail.text];
    
    NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration: defaultConfigObject delegate: nil delegateQueue: [NSOperationQueue mainQueue]];
    
    NSURL * url = [NSURL URLWithString:@"http://mobileecommerce.elasticbeanstalk.com/MobileJsonRegistraUsuario.aspx"];
    NSMutableURLRequest * urlRequest = [NSMutableURLRequest requestWithURL:url];
    NSString * params =[NSString stringWithFormat:@"strJsonBase=JsonRecuperarContrasena&strIdUsuario=%i&strEmail=%@",  intIdUser, stringReplace];
    [urlRequest setHTTPMethod:@"POST"];
    [urlRequest setHTTPBody:[params dataUsingEncoding:NSNonLossyASCIIStringEncoding]];//NSNonLossyASCIIStringEncoding  NSUTF8StringEncoding
    
    NSURLSessionDataTask * dataTask =[defaultSession dataTaskWithRequest:urlRequest
                                                       completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
                                                           NSLog(@"Response:%@ %@\n", response, error);
                                                           if(error == nil)
                                                           {
                                                               NSString * text = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
                                                               NSLog(@"Data = %@",text);
                                                           }
                                                       }];
    [dataTask resume];
    
    timerForgotPassword = nil;
    viewSaving.hidden = YES;
    
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                    message:@"Un correo de restablecimiento a sido enviado a su casilla, verifíque por favor."
                                                   delegate:nil
                                          cancelButtonTitle:@"OK"
                                          otherButtonTitles:nil];
    [alert show];
    
}

- (BOOL) validEmail:(NSString*) emailString {
    
    if([emailString length]==0){
        return NO;
    }
    
    NSString *regExPattern = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    
    NSRegularExpression *regEx = [[NSRegularExpression alloc] initWithPattern:regExPattern options:NSRegularExpressionCaseInsensitive error:nil];
    NSUInteger regExMatches = [regEx numberOfMatchesInString:emailString options:0 range:NSMakeRange(0, [emailString length])];
    
    //  NSLog(@"%lu", (unsigned long)regExMatches);
    
    if (regExMatches == 0) {
        return NO;
    } else {
        return YES;
    }
}

- (IBAction)restablecer:(id)sender {
    
    bool blnValidEmail = [self validEmail:textEmail.text];
    
    if (blnValidEmail) {
        viewSaving.hidden = NO;
        
        timerForgotPassword = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(sendRestorePassword:) userInfo:nil repeats:YES];
    }else{

        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                        message:@"El correo ingresado no es correcto, intente nuevamente por favor."
                                                       delegate:nil
                                              cancelButtonTitle:@"OK"
                                              otherButtonTitles:nil];
        [alert show];

        [textEmail becomeFirstResponder];
        
    }

}


@end



